<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>数学练习小游戏</title>
  <style>
    body {
      margin: 0;
      font-family: Arial, sans-serif;
      background-color: #f0f0f0;
      overflow: hidden;
    }
    #game-container {
      position: relative;
      width: 100vw;
      height: 100vh;
      overflow: hidden;
    }
    .question {
      position: absolute;
      font-size: 24px;
      font-weight: bold;
      color: #333;
      background-color: #fff;
      padding: 10px 20px;
      border-radius: 20px;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }
    #score {
      position: absolute;
      top: 10px;
      left: 10px;
      font-size: 20px;
      font-weight: bold;
    }
    #game-over {
      display: none;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      font-size: 36px;
      font-weight: bold;
      color: red;
    }
  </style>
</head>
<body>
  <div id="game-container">
    <div id="score">得分: 0</div>
    <div id="game-over">Game Over</div>
  </div>

  <script>
    const gameContainer = document.getElementById('game-container');
    const scoreDisplay = document.getElementById('score');
    const gameOverDisplay = document.getElementById('game-over');

    let score = 0;
    let questions = [];
    let recognition;

    // 初始化语音识别
    function initSpeechRecognition() {
      if (!('webkitSpeechRecognition' in window)) {
        alert('您的浏览器不支持语音识别功能，请使用Chrome浏览器！');
        return;
      }

      recognition = new webkitSpeechRecognition();
      recognition.continuous = true;
      recognition.interimResults = false;
      recognition.lang = 'zh-CN';
      // recognition.lang = 'en-US';

      recognition.onresult = (event) => {
        const transcript = event.results[event.results.length - 1][0].transcript.trim();
				console.log(transcript);
				console.log(transcript[transcript.length - 2]);
				checkAnswer(transcript[transcript.length - 2]);
        // checkAnswer(transcript[-1]);
      };

      recognition.onerror = (event) => {
        console.error('语音识别错误:', event.error);
      };

      recognition.start();
    }

    // 生成随机题目
    function generateQuestion() {
      let num1 = Math.floor(Math.random() * 10);
      let num2 = Math.floor(Math.random() * 10);
			num1 = Math.max(num1, num2);
			num2 = Math.min(num1, num2);
      const operation = Math.random() < 0.5 ? '+' : '-';
      const answer = operation === '+' ? num1 + num2 : num1 - num2;

      return { question: `${num1} ${operation} ${num2}`, answer };
    }

    // 添加题目到屏幕
    function addQuestion() {
      const { question, answer } = generateQuestion();
      const questionElement = document.createElement('div');
      questionElement.classList.add('question');
      questionElement.textContent = question;
      questionElement.style.left = `${Math.random() * 90}vw`;
      questionElement.style.top = '-50px';
      gameContainer.appendChild(questionElement);

      const speed = Math.random() * 2 + 1; // 下落速度
      questions.push({ element: questionElement, answer });

      moveQuestion(questionElement, speed);
    }

    // 移动题目
    function moveQuestion(element, speed) {
      let position = -50;
      const interval = setInterval(() => {
        position += speed;
        element.style.top = `${position}px`;

        if (position > window.innerHeight) {
          clearInterval(interval);
          removeQuestion(element);
          updateScore(-1); // 扣分
        }
      }, 16);

      element.dataset.interval = interval;
    }

    // 移除题目
    function removeQuestion(element) {
      element.remove();
      questions = questions.filter(q => q.element !== element);
    }

    // 检查答案
    function checkAnswer(answer) {
      const parsedAnswer = parseInt(answer, 10);
      for (let i = 0; i < questions.length; i++) {
        const { element, answer: correctAnswer } = questions[i];
        if (parsedAnswer === correctAnswer) {
          clearInterval(element.dataset.interval);
          explodeQuestion(element);
          updateScore(1); // 加分
          questions.splice(i, 1);
          break;
        }
      }
    }

    // 爆炸效果
    function explodeQuestion(element) {
      element.style.transition = 'transform 0.2s, opacity 0.2s';
      element.style.transform = 'scale(1.5)';
      element.style.opacity = '0';

      setTimeout(() => {
        element.remove();
      }, 200);
    }

    // 更新分数
    function updateScore(delta) {
      score += delta;
      scoreDisplay.textContent = `得分: ${score}`;

      if (score < 0) {
        endGame();
      }
    }

    // 游戏结束
    function endGame() {
      gameOverDisplay.style.display = 'block';
      recognition.stop();
			clearInterval(addQuestion);

      questions.forEach(({ element }) => {
        clearInterval(element.dataset.interval);
        element.remove();
      });

      questions = [];
    }

    // 定时生成题目
    function startGame() {
      initSpeechRecognition();
      setInterval(addQuestion, 2000); // 每2秒生成一个新题目
    }

    // 开始游戏
    startGame();
  </script>
</body>
</html>